using System;
using System.Collections.Generic;
using System.Text;

namespace cwebber
{
    public class Logger : Webber.IExportMonitor
    {
        System.IO.StreamWriter m_log;
        bool m_bLog;

        public Logger()
        {
            m_bLog = false;
        }

        public bool SetTextLog(string logfile)
        {
            // if already opened close the previous one
            if (m_bLog)
            {
                m_log.Close();
                m_bLog = false;
            }

            // try to create file based on path
            string path = System.IO.Path.GetFullPath(logfile);
            try
            {
                m_log = new System.IO.StreamWriter(path, true);
                m_bLog = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: Failed to enable logging (" + e.Message + "). Logging will not occur for this export operation.");
                m_bLog = false;
            }

            return m_bLog;
        }

        public void CloseTextLog()
        {
            if (m_bLog)
            {
                m_log.Close();
            }
        }

        // Implement the parts of status monitor we want
        public void SetRange(int min, int max) { }
        public void Increment(int i) { }
        public void Reset() { }
        public void AppendLog(string msg)
        {
            // write to console
            Console.WriteLine(msg);
            
            // write to log if its enabled
            if (m_bLog)
            {
                try
                {
                    m_log.WriteLine(msg);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: Failed to write to log (" + e.Message + "). Disabling logging.");
                    m_bLog = false;
                }
            }    
        }
        public void ClearLog() {}
        public void CurrentStatus(string msg)
        {
            // note: we eat up blank messages
            
            // same as append
            if (msg.Trim() != "") AppendLog(msg);
        }
        public void SetDone(bool status) { }
        public bool ShouldStop() { return false; }
    }
}
